<?php
Class admin_loaiController Extends baseController {

	public function index() { 
		$loaiModel = new loaitivi();
		
		$lstloai = $loaiModel->getAllLoaiTiviByWhere('', 'TenLoai');
		$this->registry->template->lstLoai = $lstloai;
		
		$this->registry->template->show('admin/loai_view');
	}
	
	public function edit(){
		if(isset($_REQUEST['loai_id'])){
			$loai_id = $_REQUEST['loai_id'];
			$loaiModel = new loaitivi();
			$loai = $loaiModel->getLoaiTiviById($loai_id);
			if(count($loai)>0){
				$this->registry->template->loai = $loai;	
			}
		}
		$this->registry->template->show('admin/loai_edit');	
	}
	
	public function save(){
			
			$loai = new loaitivi();
			$loai->TenLoai = trim($_POST['ttenloai']); //echo $loai->TenLoai;
			$loai->TrangThai = $_POST['rtrangthai'];
			
			if(isset($_REQUEST['loai_id'])) $loai->id = trim($_GET['loai_id']);
			//else $loai->id = trim($_POST['ttendangnhap']);
			
			
			//lay danh sach user de kiem tra ten dang nhap va email xem da co chua
			if(isset($_REQUEST['loai_id'])) $lstloai = $loai->getAllLoaiTiviByWhere('id <> "'.$loai->id.'"','');
			else $lstloai = $loai->getAllLoaiTiviByWhere('','');
			if(count($lstloai)>0)
			{
				//kiem tra neu ton tai ten dang nhap do roi thi hien thong bao
				foreach($lstloai as $h){
					if((strtolower(trim($h->TenLoai)) == strtolower(trim($loai->TenLoai)))){
						$this->registry->template->message_user = 'Tên loại đã tồn tại.';
						$this->registry->template->loai = $loai;
						$this->registry->template->show('admin/loai_edit');
						return;	
					}
				}
			}
			if(isset($_REQUEST['loai_id'])){
				//$loai->id = $_GET['loai_id'];
				$rs = $loai->update($loai);
				if($loai->TrangThai == '0'){
					$tiviModel = new tivi();
					$tiviModel->updateTrangThaiByLoai("0",$loai->id);
				}
			}
			else{
				
				$rs = $loai->insert($loai);
			}
			
			if($rs){
				echo '<script>alert("thành công.");</script>';
				header('location:'.__URL_BASE.'index.php?rt=admin_loai');
				exit;
			}
			else{
				echo '<script>alert("Có lỗi xảy ra.");</script>';
			}
		}
		
		public function delete(){
			if(isset($_REQUEST['loai_id'])){
				$loaiModel = new loaitivi();
				$loaiModel->delete($_REQUEST['loai_id']);
				header('location:'.__URL_BASE.'index.php?rt=admin_loai');
				exit;
			}
		}
}
?>